<template>
    <div>
        <Row type="flex" justify="space-between" class="ivu-mb-8">
            <Col>
                <Button type="primary" @click="changeEdit(false)" :disabled="!selection.length" v-hasC="{
                            name: '-v1-marketing-data-update-config4',
                            flag: '/v1/marketing/data/update-config',
                        }">批量编辑</Button>
                <Button type="error" class="ivu-ml-8" @click="handleDelete" :disabled="!selection.length" v-hasC="{
                            name: '-v1-marketing-data-delete-config2',
                            flag: '/v1/marketing/data/delete-config',
                        }">批量删除</Button>
            </Col>
            <Col><Button type="primary" @click="changeEdit(true)" :disabled="disabledadd">新增</Button></Col>
        </Row>
        <Row type="flex" justify="end" class="ivu-mb-8 ivu-pr-16" style="font-size:16px" v-if="config_default.id">
            <Col>
                <span>通配渠道：</span>
                <span><span v-if="config_default.source_channel_pname">{{config_default.source_channel_pname}}-</span>{{config_default.source_channel_name}}</span>
            </Col>
            <Col class="ivu-pl-16">
                <a @click="changeEdit(false,config_default)" v-hasC="{
                            name: '-v1-marketing-data-update-config-default2',
                            flag: '/v1/marketing/data/update-config-default',
                        }">编辑</a>
                <Divider type="vertical"/>
                <a @click="changeDelete(config_default)" style="color:#ed4014" v-hasC="{
                            name: '-v1-marketing-data-delete-config-default',
                            flag: '/v1/marketing/data/delete-config-default',
                        }">删除</a>
            </Col>
        </Row>
        <Table :columns="columns" :data="data" :loading="loading" @on-selection-change="selectionChange">
            <template slot-scope="{ row }" slot="source_channel_pname">
                <span v-if="row.source_channel_pname">{{row.source_channel_pname}}</span>
                <span v-else>{{row.source_channel_name}}</span>
            </template>
            <template slot-scope="{ row }" slot="source_channel_name">
                <span v-if="row.source_channel_pname">{{row.source_channel_name}}</span>
                <span v-else></span>
            </template>
            <template slot-scope="{ row }" slot="action">
                <a @click="handleEdit(row)" v-hasC="{
                            name: '-v1-marketing-data-update-config4',
                            flag: '/v1/marketing/data/update-config',
                        }">编辑</a>
                <Divider type="vertical"/>
                <a @click="handleDelete(row)" style="color:#ed4014" v-hasC="{
                            name: '-v1-marketing-data-delete-config2',
                            flag: '/v1/marketing/data/delete-config',
                        }">删除</a>
            </template>
            <template slot="footer">
                <Page
                    show-total show-elevator
                    show-sizer transfer
                    :total="total"
                    :current.sync="params.page"
                    :page-size="params.pageSize"
                    :page-size-opts="pageOpts"
                    @on-change="changepage"
                    @on-page-size-change="changepageSize"
                    style="text-align: center;"
                />
            </template>
        </Table>
        <Modal v-model="editModal" :title="edit?'新增':'编辑'" @on-cancel="handleCancel('editParams')">
            <Form ref="editParams" :model="editParams" :rules="ruleValidate">
                <FormItem>
                    <RadioGroup v-model="editParams.type" v-if="!disabled">
                        <Radio :label="1" v-hasC="{
                            name: '-v1-marketing-data-update-config',
                            flag: '/v1/marketing/data/update-config',
                        }">常规</Radio>
                        <Radio :label="2" v-hasC="{
                            name: '-v1-marketing-data-update-config-default',
                            flag: '/v1/marketing/data/update-config-default',
                        }" :disabled="config_default.id">通配</Radio>
                    </RadioGroup>
                </FormItem>
                <template v-if="editParams.type === 1">
                    <div v-for="(item, index) in editParams.list" :key="index">
                        <Row type="flex" align="middle" >
                            <Col span="12" class="ivu-mr-8">
                                <FormItem :prop="'list.' + index + '.keyword'"
                                :rules="{required: true, message: '请输入渠道标识，多个用“，”分隔', trigger: 'blur'}">
                                    <Input type="text" v-model="item.keyword" placeholder="请输入渠道标识，多个用“，”分隔"></Input>
                                </FormItem>
                            </Col>
                            <Col span="8" class="ivu-mr-8">
                                <FormItem :prop="'list.' + index + '.source_channel_id'"
                                :rules="{required: true, message: '请选择渠道', trigger: 'change'}">
                                    <Select v-model="item.source_channel_id" placeholder="请选择渠道" filterable clearable @on-change="changeChannel">
                                        <Option v-for="item in channelList" :value="item.id" :key="item.id" :disabled="item.disabled">{{ item.source_name }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="3" v-if="edit">
                                <FormItem>
                                    <Button type="primary" class="ivu-mr-8" icon="md-add" v-if="+index === +editParams.list.length - 1" @click="channelAdd"></Button>
                                    <Button type="error" v-if="+index !== +editParams.list.length - 1" icon="md-close" @click="channelDel(index)"></Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </div>
                </template>
                <FormItem v-else prop="source_channel_id">
                    <Select v-model="editParams.source_channel_id" placeholder="请选择渠道" clearable>
                        <Option v-for="item in channelList" :value="item.id" :key="item.id">{{ item.source_name }}</Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button class="ivu-mr-8" @click="handleCancel('editParams')">取消</Button>
                <Button type="primary" @click="handleSubmit('editParams')">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import { marketingdataconfiglist, marketingdataupdateconfigdefault, marketingdataupdateconfig, marketingdatadeleteconfigdefault, marketingdatadeleteconfig } from '@/api/hqapi/networkMarketing.js';
    import { settingsourcechannelview } from '@/api/hqapi';
    export default {
        name: 'channelconfiguration',

        data () {
            return {
                loading: false,
                disabled: false,
                disabledadd: false,
                pageOpts: [10, 20, 50, 100],
                total: 0,
                data: [],
                columns: [
                    { type: 'selection', align: 'center', width: 60 },
                    { title: '一级渠道', key: 'source_channel_pname', slot: 'source_channel_pname', minWidth: 100 },
                    { title: '二级渠道', key: 'source_channel_name', slot: 'source_channel_name', minWidth: 100 },
                    { title: '标识', key: 'keyword', minWidth: 120 },
                    { title: '操作', slot: 'action', width: 120 }
                ],
                params: { page: 1, pageSize: 20 },
                config_default: { created_at: '', id: '', operation_id: '', project_id: '', source_channel_id: '', source_channel_name: '', updated_at: '' },
                editParams: { type: 1, list: [{ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' }], source_channel_id: '', id: '' },
                selection: [],
                ruleValidate: {
                    source_channel_id: [{ required: true, message: '请选择渠道', trigger: 'change' }]
                },
                edit: false,
                editModal: false,
                channelList: []

            };
        },

        mounted () {
            let menus = JSON.parse(localStorage.getItem('menus'));
            let power = menus.action;
            let flag = power.find(
                (ee) =>
                    ee.flag === '/v1/marketing/data/update-config' &&
                    ee.marking === '-v1-marketing-data-update-config'
            );
            let flags = power.find(
                (ee) =>
                    ee.flag === '/v1/marketing/data/update-config-default' &&
                    ee.marking === '-v1-marketing-data-update-config-default'
            );
            if (!flag && !flags) this.disabledadd = true;
            this.initial()
        },

        methods: {
            initial () {
                settingsourcechannelview({ page: 0, pageSize: 0 }).then(res => {
                    for (let item of res.list) {
                        if (+item.status === 1) {
                            if (item.children.length > 0) {
                                for (let items of item.children) {
                                    if (+items.status === 1) {
                                        this.channelList.push({ id: items.id, source_name: `${item.source_name}-${items.source_name}`, disabled: false })
                                    }
                                }
                            } else this.channelList.push({ id: item.id, source_name: item.source_name, disabled: false })
                        }
                    }
                    this.askData()
                })
            },
            askData () {
                this.loading = true
                this.channelList.forEach(item => {
                    item.disabled = false
                });
                marketingdataconfiglist(this.params).then(res => {
                    this.channelList.forEach(item => {
                        res.list.forEach(items => {
                            if (items.source_channel_id === item.id) {
                                item.disabled = true
                            }
                        });
                    });
                    this.config_default = res.config_default
                    this.data = res.list
                    this.total = res.total
                    this.loading = false
                })
            },
            changepage (e) {
                this.params.page = e;
                this.askData()
            },
            changepageSize (e) {
                this.params.page = 1;
                this.params.pageSize = e;
                this.askData()
            },
            selectionChange (selection) {
                this.selection = selection
            },
            changeEdit (bool, bools) {
                this.disabled = false
                this.edit = bool
                if (bool) {
                    let menus = JSON.parse(localStorage.getItem('menus'));
                    let power = menus.action;
                    let flag = power.find(
                        (ee) =>
                            ee.flag === '/v1/marketing/data/update-config' &&
                            ee.marking === '-v1-marketing-data-update-config'
                    );
                    if (flag) this.editParams = { type: 1, list: [{ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' }], source_channel_id: '', id: '' }
                    else this.editParams = { type: 2, list: [{ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' }], source_channel_id: '', id: '' }
                } else {
                    this.disabled = true
                    if (bools) {
                        this.editParams.type = 2
                        this.editParams.source_channel_id = bools.source_channel_id
                        this.editParams.id = bools.id
                    } else {
                        this.editParams.type = 1
                        this.editParams.list = []
                        for (let item of this.selection) {
                            this.editParams.list.push({ old_source_channel_id: JSON.parse(JSON.stringify(item.source_channel_id)), source_channel_id: item.source_channel_id, keyword: item.keyword, id: item.id })
                        }
                    }
                }
                this.editModal = true
            },
            handleEdit (row) {
                this.disabled = true
                this.editParams.type = 1
                this.editParams.list = [{ old_source_channel_id: JSON.parse(JSON.stringify(row.source_channel_id)), source_channel_id: row.source_channel_id, keyword: row.keyword, id: row.id }]
                this.editModal = true
            },
            changeDelete (row) {
                this.$Modal.confirm({
                    title: '删除提示',
                    content: `<p>是否删除通配渠道配置？删除后渠道将无法自动匹配。</p>`,
                    onOk: () => {
                        marketingdatadeleteconfigdefault({ id: row.id }).then(res => {
                            this.$Message.success('删除通配渠道成功');
                            this.askData()
                        })
                    }
                });
            },
            handleDelete (row) {
                this.$Modal.confirm({
                    title: '删除提示',
                    content: `<p>是否批量删除渠道配置？删除后渠道将无法自动匹配。</p>`,
                    onOk: () => {
                        let source_channel_id = ''
                        console.log(this.selection, source_channel_id, row)
                        if (row.source_channel_id) {
                            source_channel_id = row.source_channel_id
                        } else {
                            this.selection.forEach(item => {
                                source_channel_id += `,${item.source_channel_id}`
                            })
                        }
                        marketingdatadeleteconfig({ source_channel_id: source_channel_id }).then(() => {
                            this.$Message.success('删除成功');
                            this.askData();
                        });
                    }
                });
            },
            changeChannel () {
                this.channelList.forEach(item => {
                    item.disabled = false
                });
                this.channelList.forEach(item => {
                    this.editParams.list.forEach(items => {
                        if (items.source_channel_id === item.id) {
                            item.disabled = true
                        }
                    });
                });
            },
            channelAdd () {
                this.editParams.list.push({ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' })
            },
            channelDel (index) {
                this.editParams.list.splice(index, 1)
            },
            handleCancel (name) {
                this.$refs[name].resetFields();
                this.editModal = false
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.editParams.type === 1) {
                            let list = this.editParams.list
                            marketingdataupdateconfig({ list }).then(res => {
                                if (this.edit) this.$Message.success('新增成功');
                                else this.$Message.success('批量编辑成功');
                                this.selection = []
                                this.editParams = { type: 1, list: [{ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' }], source_channel_id: '', id: '' }
                                this.askData()
                                this.editModal = false
                            })
                        } else {
                            marketingdataupdateconfigdefault({ source_channel_id: this.editParams.source_channel_id, id: this.editParams.id }).then(res => {
                                if (this.edit) this.$Message.success('新增通配渠道成功');
                                else this.$Message.success('编辑通配渠道成功');
                                this.selection = []
                                this.editParams = { type: 1, list: [{ old_source_channel_id: '', source_channel_id: '', keyword: '', id: '' }], source_channel_id: '', id: '' }
                                this.askData()
                                this.editModal = false
                            })
                        }
                    }
                })
            }
        }
    };
</script>
